from app.file.model import File, FileRelation
import os
from flask import current_app
from common import constant
from flask import g
import time
from flask import safe_join
# from common.utils.excel import export_to_excel
import pandas as pd
from io import StringIO
import json


def get_files_by_belong(belong_id, belong_type):
    relations = FileRelation.query.filter_by(belong_id=belong_id, belong_type=belong_type).all()
    files = []
    for relation in relations:
        file = File.query.filter_by(id=relation.file_id).first()
        files.append(file)
    return files


# 获取用户文件路径
def get_user_folder_path():
    folder_path = os.path.join(
        current_app.root_path,
        constant.USER_FILE_BASE_FOLDER_PATH,
        str(g.user_id))
    if not os.path.exists(folder_path):  # 如果不存在则创建
        os.makedirs(folder_path)
    return folder_path


# 生成excel文件路径
def get_excel_file_path(file_name):
    folder_path = get_user_folder_path()
    time_str = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    return safe_join(folder_path, "{}_{}.xlsx".format(file_name, time_str))


# 将json转成成dataframe
def json_to_dataframe(json_data):
    df = pd.read_json(StringIO(json.dumps(json_data)), dtype={}, orient='records')
    return df


def get_img_files_from_belong(belong_id, belong_type):
    files = get_files_by_belong(belong_id, belong_type)
    img_files = []
    for file in files:
        if file.file_type == constant.FileType.IMG:
            img_files.append(file)
    return img_files
# # 将json保存成excel文件
# def save_json_to_excel(json_data, file_name):
#     folder_path = get_user_folder_path()
#     time_str = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
#     file_path = safe_join(folder_path, "{}_{}.xlsx".format(file_name, time_str))
#     export_to_excel(file_path, json_data, dtype={
#         # '操作时间': datetime.datetime
#     })
#     return file_path

# def add_images_to_belong(belong_id, belong_type, image_ids):
#     if image_ids or len(image_ids) == 0:
#         for image_id in image_ids:
#             FileRelation.create(
#                 file_id=image_id, belong_id=belong_id,
#                 belong_type=belong_type)